from dash import html, dcc, dash_table
import dash_bootstrap_components as dbc
import time
# import dash_table

# 设备台账页面布局
# 在布局的最开始添加
layout = html.Div([
    dcc.Store(id='url-equipment-category-store') ,
    dcc.Store(id='url-price-range-store') ,
    dcc.Store(id='url-params-trigger'),
    # 添加CSS链接
    html.Link(
        rel='stylesheet',
        href='/static/css/equipment.css'
    ),

    # 添加初始化触发器，设置初始值为时间戳
    dcc.Store(id='init-load-trigger', data=int(time.time()), storage_type='session'),
    dcc.Store(id='url-device-id-store', data=None),
    dcc.Store(id='auto-select-trigger-store', data=None),
    dcc.Store(id='url-org-store', data=None), # <-- 新增：存储从URL解析的org参数

    # 页面标题
    # html.H2("设备台账管理", className="page-title mb-3"),

    # 其余布局代码...
    html.Div([
        # 左侧筛选条件区域 (20% 宽度)
        html.Div([
            html.Div([
                html.H5("筛选条件", className="filter-title"),

                # 所属医院筛选
                html.Div([
                    html.Label("所属医院、科室"),
                    dcc.Dropdown(
                        id='hospital-filter',
                        options=[],
                        placeholder="选择医院",
                        multi=True,
                        searchable=True
                    ),
                    dcc.Dropdown(
                        id='hospital-dept-filter',
                        options=[],
                        placeholder="选择科室",
                        multi=True,
                        searchable=True
                    )
                ], className="filter-item", style={"borderBottom": "1px dashed #ccc", "paddingBottom": "10px", "marginBottom": "10px"}), # 添加底部虚线边框和间距


                html.Div([
                    html.Label("设备ID、名称"),
                    dcc.Input(id="filter-device-id", type="text", placeholder="请输入设备ID", style={"width": "100%"}),
                    dcc.Input(id="filter-device-name", type="text", placeholder="请输入设备名称", style={"width": "100%"}),
                ], style={"borderBottom": "1px dashed #ccc", "paddingBottom": "10px", "marginBottom": "10px"}), # 添加底部虚线边框和间距


                # 采购时间段筛选
                html.Div([
                    html.Label("采购时间段"),
                    # 修改此Div的样式以使用flexbox
                    html.Div([
                        dcc.DatePickerSingle(
                            id='purchase-date-start',
                            placeholder='开始日期',
                            className="mb-1",
                            style={"width": "48%", "marginRight": "4%", "color": "white !important"} # 添加 color: "white !important"
                        ),
                        dcc.DatePickerSingle(
                            id='purchase-date-end',
                            placeholder='结束日期',
                            style={"width": "48%", "color": "white !important"} # 添加 color: "white !important"
                        )
                    ], style={"display": "flex", "justifyContent": "space-between"}) # 使用flexbox布局
                ], className="filter-item", style={"borderBottom": "1px dashed #ccc", "paddingBottom": "10px", "marginBottom": "10px"}), # 添加底部虚线边框和间距


                # 设备类型筛选
                html.Div([
                    html.Label("设备分类、品牌"),
                    dcc.Dropdown(
                        id='equipment-type-filter',
                        options=[],
                        placeholder="选择设备分类",
                        multi=True,
                        searchable=True,
                        # 添加点击事件属性
                        # n_clicks_timestamp=0
                    )
                ], className="filter-item", style={ "paddingBottom": "10px", "marginBottom": "10px"}), # 添加底部虚线边框和间距

                # 品牌筛选
                html.Div([

                    dcc.Dropdown(
                        id='brand-filter',
                        options=[],
                        placeholder="选择品牌",
                        multi=True,
                        searchable=True,
                        # 添加点击事件属性
                        # n_clicks_timestamp=0
                    )
                ], className="filter-item", style={"borderBottom": "1px dashed #ccc", "paddingBottom": "10px", "marginBottom": "10px"}), # 添加底部虚线边框和间距

                # 价格区间筛选
                html.Div([
                    html.Label("价格区间(万元)"),
                    # 修改此Div的样式以使用flexbox
                    html.Div([
                        dcc.Input(id='price-min', type='number', placeholder='最低价', style={"width": "48%", "marginRight": "4%"}), # 调整宽度和右边距
                        dcc.Input(id='price-max', type='number', placeholder='最高价', style={"width": "48%"}) # 调整宽度
                    ], style={"display": "flex", "justifyContent": "space-between"}) # 使用flexbox布局
                ], className="filter-item", style={"borderBottom": "1px dashed #ccc", "paddingBottom": "10px", "marginBottom": "10px"}), # 添加底部虚线边框和间距

                
                # 筛选按钮
                html.Div([
                    html.Button("筛选", id="filter-button", className="btn btn-primary me-2", style={"boxShadow": "2px 2px 5px #111"}), # 添加阴影
                    html.Button("重置", id="reset-button", className="btn btn-secondary", style={"boxShadow": "2px 2px 5px #111"}) # 添加阴影
                ], className="filter-buttons", style={"borderBottom": "1px dashed #ccc", "paddingBottom": "10px", "marginBottom": "10px", "display": "flex", "justifyContent": "center"}), # 添加底部虚线边框和间距，并使用flexbox居中

                #  dcc.Download(id="download-excel"),
                #导出设备列表
                 dcc.Download(id="export-data"),
                 html.Div([
                    # 导出按钮
                    html.Form(
                        [
                            dcc.Input(id="hidden-device-ids", name="device_ids", type="hidden"),
                        ],
                        id="download-qrcode-form",
                        action="/equipment/generate_qrcodes",
                        method="post",
                        target="_blank",  # 新窗口下载
                        style={"display": "none"}
                    ),
                    html.Div(id="qrcode-area"),
                    html.Button("导出当前列表", id="export-excel-btn", n_clicks=0, style={"marginTop": "10px", "width": "100%", "boxShadow": "2px 2px 5px #111"}), # 添加阴影
                    html.Button("报修二维码", id="btn-generate-qrcodes", n_clicks=0, style={"width": "100%", "height": "40px", "marginTop": "20px","background": "#1976d2", "color": "#fff", "boxShadow": "2px 2px 5px #111"}), # 添加阴影
                    dbc.Modal(
                        [
                            dbc.ModalHeader("报修二维码"),
                            dbc.ModalBody(id="qrcode-modal-body"),
                        ],
                        id="qrcode-modal",
                        is_open=False,
                        size="xl"
                    ),
                ], className="filter-item", style={"paddingBottom": "10px"}), # 最后一个区域不需要底部边框，但保留底部内边距
            ], className="filter-container")
        ], className="filter-column", style={"width": "20%", "padding": "0 5px", "border": "1px dashed #ccc", "height": "100%"}), # 移除 float: left, 添加 height: 100%

        # 中间设备列表区域 (40% 宽度)
        html.Div([
            html.Div([
                html.H5("设备列表", className="list-title"),

                # 简化的设备列表表格 - 只显示关键信息
                dash_table.DataTable(
                    id='equipment-table',
                    columns=[
                        # 添加设备ID列
                        {"name": "设备ID", "id": "id"},

                        {"name": "设备名称", "id": "name"},
                        {"name": "设备分类", "id": "category"},
                        {"name": "品牌", "id": "brand"},
                        {"name": "型号", "id": "model"},
                        {"name": "所属机构", "id": "org_name"},
                        {"name": "科室", "id": "department"},
                        {"name": "购买日期", "id": "purchase_date"},
                        {"name": "价格(万))", "id": "price"},
                        {"name": "运行状态", "id": "status"},
                    ],
                    page_current=0,
                    page_size=300,
                    page_action='custom',
                    sort_action='custom',
                    sort_mode='multi',
                    sort_by=[],
                    filter_action='none',
                    style_table={'overflowX': 'auto', 'height': 'calc(100vh - 235px)', 'overflowY': 'auto'},
                    # 添加或修改 style_cell 属性以添加右侧边框
                    style_cell={
                        'textAlign': 'left', # 可以保留原有的对齐方式
                        'minWidth': '80px', 'width': '150px', 'maxWidth': '200px', # 可以保留原有的宽度设置
                        'overflow': 'hidden',
                        'textOverflow': 'ellipsis',
                        'borderRight': '1px solid #dee2e6' # 添加右侧边框
                    },
                    # 可以选择性地为最后一列移除右侧边框，使其看起来更整洁
                    style_cell_conditional=[
                        {
                            'if': {'column_id': 'status'}, # 假设 'status' 是最后一列的 id
                            'borderRight': 'none'
                        }
                    ],
                    # 合并后的 style_header 属性
                    style_header={
                        'backgroundColor': '#1a3a5f',  # 深蓝色
                        'color': '#ffffff',
                        'fontWeight': 'bold',
                        'borderRight': '1px solid #dee2e6' # 添加右侧边框
                    },
                    # 可以选择性地为最后一列表头移除右侧边框
                    style_header_conditional=[
                        {
                            'if': {'column_id': 'status'}, # 假设 'status' 是最后一列的 id
                            'borderRight': 'none'
                        }
                    ],
                    style_data_conditional=[
                        {
                            'if': {'row_index': 'odd'},
                            'backgroundColor': '#234a78'  # 浅蓝色
                        },
                        {
                            'if': {'row_index': 'even'},
                            'backgroundColor': '#1a3a5f'  # 深蓝色
                        },
                        {
                            'if': {'state': 'selected'},
                            'backgroundColor': '#e6f7ff',
                            'border': '1px solid #91d5ff'
                        }
                    ],
                    row_selectable='single',
                    selected_rows=[]
                ),

                # 分页信息紧挨着表格
                html.Div(id='pagination-info', className="pagination-info mt-2")
            ], className="list-container")
        ], className="list-column", style={"width": "40%", "padding": "0 5px", "border": "1px dashed #ccc", "height": "100%"}), # 移除 float: left, 添加 height: 100%

        # 右侧设备详细信息区域 (40% 宽度)
        html.Div([
            html.Div([
                html.H5("设备详细信息", className="detail-title"),

                # 详细信息展示区域
                html.Div(id='equipment-details', children=[
                    html.H4("请在左侧列表中选择一个设备查看详细信息", className="text-center text-muted mt-5")
                ], className="detail-content")
            ], className="detail-container")
        ], className="detail-column", style={"width": "40%", "padding": "0 5px", "border": "1px dashed #ccc", "height": "100%"}) # 移除 float: left, 添加 height: 100%
    ], className="row-container", style={"display": "flex", "flexWrap": "nowrap", "margin": "0 -5px", "height": "calc(100vh - 100px)"}), # 添加 height 以便子元素可以拉伸

    # 添加清除浮动的元素 (float 已移除，此行可能不再需要，但保留无害)
    html.Div(style={"clear": "both"})
], className="equipment-page")

# 设备详细信息展示模板
def generate_equipment_detail(equipment_data):
    """生成设备详细信息展示"""
    if not equipment_data:
        return html.H4("未找到设备信息", className="text-center text-muted mt-5")

    return html.Div([
        # 基本信息卡片
        html.Div([
            html.H6("基本信息", className="detail-section-title"),
            html.Div([
                html.Div([
                    html.P(f"设备ID: {equipment_data.get('product_id', '无')}"),
                    html.P(f"产品编号: {equipment_data.get('product_code', '无')}"),
                    html.P(f"设备名称: {equipment_data.get('name', '无')}"),
                    html.P(f"设备类别: {equipment_data.get('category', '无')}"),
                    html.P(f"设备类型: {equipment_data.get('type', '无')}"),
                ], className="detail-col", style={"width": "50%", "float": "left"}),
                html.Div([
                    html.P(f"品牌: {equipment_data.get('brand', '无')}"),
                    html.P(f"型号: {equipment_data.get('model', '无')}"),
                    html.P(f"所属医院: {equipment_data.get('org_name', '无')}"),
                    html.P(f"采购日期: {equipment_data.get('purchase_date', '无')}"),
                    html.P(f"价格: {equipment_data.get('price', '无')}万元"),
                ], className="detail-col", style={"width": "50%", "float": "left"}),
                html.Div(style={"clear": "both"})
            ], className="detail-row")
        ], className="detail-section"),

        # 技术参数卡片
        html.Div([
            html.H6("技术参数", className="detail-section-title"),
            html.Div([
                html.Div([
                    html.P(f"软件版本: {equipment_data.get('software_version', '无')}"),
                    html.P(f"硬件版本: {equipment_data.get('hardware_version', '无')}"),
                ], className="detail-col", style={"width": "50%", "float": "left"}),
                html.Div([
                    html.P(f"网络地址: {equipment_data.get('network_address', '无')}"),
                    html.P(f"使用年限: {equipment_data.get('service_life', '无')}年"),
                ], className="detail-col", style={"width": "50%", "float": "left"}),
                html.Div(style={"clear": "both"})
            ], className="detail-row"),
            html.P(f"技术参数: {equipment_data.get('technical_parameters', '无')}")
        ], className="detail-section"),

        # 厂商信息卡片
        html.Div([
            html.H6("厂商信息", className="detail-section-title"),
            html.Div([
                html.Div([
                    html.P(f"生产厂家: {equipment_data.get('manufacturer', '无')}"),
                    html.P(f"厂家所在国: {equipment_data.get('manufacturer_country', '无')}"),
                    html.P(f"生产日期: {equipment_data.get('production_date', '无')}"),
                ], className="detail-col", style={"width": "50%", "float": "left"}),
                html.Div([
                    html.P(f"出厂日期: {equipment_data.get('factory_date', '无')}"),
                    html.P(f"厂家代表人: {equipment_data.get('factory_representative', '无')}"),
                    html.P(f"厂家联系方式: {equipment_data.get('factory_contact_info', '无')}"),
                ], className="detail-col", style={"width": "50%", "float": "left"}),
                html.Div(style={"clear": "both"})
            ], className="detail-row")
        ], className="detail-section"),

        # 运行状态卡片
        html.Div([
            html.H6("运行状态", className="detail-section-title"),
            html.Div([
                html.Div([
                    html.P(f"运行状态: {equipment_data.get('running_status', '无')}"),
                    html.P(f"上次维护日期: {equipment_data.get('last_maintenance_date', '无')}"),
                    html.P(f"下次维护日期: {equipment_data.get('next_maintenance_date', '无')}"),
                ], className="detail-col", style={"width": "50%", "float": "left"}),
                html.Div([
                    html.P(f"维护次数: {equipment_data.get('maintenance_count', '无')}"),
                    html.P(f"故障次数: {equipment_data.get('fault_count', '无')}"),
                    # html.P(f"完好率: {equipment_data.get('completion_rate', '无')}%"),
                ], className="detail-col", style={"width": "50%", "float": "left"}),
                html.Div(style={"clear": "both"})
            ], className="detail-row")
        ], className="detail-section")
    ], className="equipment-details")



